<template>
    <div class="common-layout">
        <el-container>
            <!-- <el-header style="display: flex; align-items: center;">
                <div class="item-text" style="flex: 1;"></div>
                <div style="flex: 1;">
                    <el-row align="middle" :gutter="20" justify="start">
                        <el-col :span="8">
                            <el-form-item>
                                <el-select v-model="searchModel.ProcessName" clearable filterable placeholder="请输入工序名称"
                                    style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;margin-top: 20px;">
                                    <el-option v-for="item in processOptions" :key="item.id" :label="item.processName"
                                        :value="item.processName" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="primary" @click="SearchList"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                搜索
                            </el-button>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="success" @click="InsertData()"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                新增
                            </el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-header> -->

            <div class="view-header" style="display: flex; justify-content: space-between;margin-top: 15px;">
                <div class="desc-text">
                    <i class="el-icon-s-grid" />
                    <span>报工列表</span>
                </div>
                <div>
                    <el-select v-model="searchModel.ProcessName" clearable filterable placeholder="请输入工序名称"
                        style="width: 240px;font-size: 15px; padding: 0 15px;">
                        <el-option v-for="item in processOptions" :key="item.id" :label="item.processName"
                            :value="item.processName" />
                    </el-select>
                    <el-button type="primary" @click="SearchList">
                        <i class="el-icon-search"></i>搜索
                    </el-button>
                    <el-button type="success" @click="SearchList">
                        <i class="el-icon-refresh"></i>刷新
                    </el-button>
                    <el-button type="success" @click="InsertData()">
                        <i class="el-icon-plus"></i>新增
                    </el-button>
                </div>
            </div>

            <div class="mian-flex">
                <!-- 订单列表 -->
                <div class="table-container" v-loading="loading">
                    <!-- <div class="section-title">报工列表</div> -->

                    <!-- 报工列表 -->
                    <div class="table-info mes-table">
                        <el-table :data="detailTableData.filter(row => row.status !== 6)" stripe border
                            style="width: 100%;" max-height="550">
                            <!-- 序号列 -->
                            <el-table-column type="index" width="50" />
                            <!-- 选择列 -->
                            <el-table-column type="selection" width="50" align="center" />
                            <el-table-column label="工单" width="300" align="center">
                                <template #default="scope">
                                    <el-link type="primary" @click="showWorkOrderDetail(scope.row.reportWorkOrder_Id, scope.row)">
                                        {{ scope.row.workOrderCode }} | {{ scope.row.inventoryName }}
                                    </el-link>
                                </template>
                            </el-table-column>
                            <el-table-column label="工序名称" prop="processName" width="150" />
                            <!-- 单据编号列，点击显示订单明细 -->
                            <!-- <el-table-column label="工单编号" prop="workOrderCode" width="150" align="center">
                                <template #default="scope">
                                    <el-link type="primary" @click="showWorkOrderDetail(scope.row)">
                                        {{ scope.row.workOrderCode }}
                                    </el-link>
                                </template>
                            </el-table-column> -->
                            <el-table-column prop="inventoryName" label="存货名称" width="150" align="center" />
                            <el-table-column prop="inventoryCode" label="存货编号" width="250" align="center" />
                            <el-table-column prop="specificationModel" label="产品规格" width="100" align="center" />
                            <el-table-column prop="teamName" label="班组名称" width="100" align="center" />
                            <el-table-column prop="vendName" label="设备名称" width="100" align="center" />
                            <el-table-column prop="manHour" label="标准工时" width="120" align="center" />
                            <!-- <el-table-column prop="departmentName" label="关联单据" width="120" align="center" /> -->
                            <!-- <el-table-column label="工序状态" width="120" align="center">
                                <template #default="scope">
                                    <span v-if="scope.row.status === '1'" type="success">未开始</span>
                                    <span v-if="scope.row.status === '2'" type="warning">进行中</span>
                                    <span v-if="scope.row.status === '3'" type="danger">已完成</span>
                                    <span v-if="scope.row.status === '4'" type="danger">已撤回</span>
                                    <span v-if="scope.row.status === '5'" type="danger">已取消</span>
                                </template>
                            </el-table-column> -->
                            <el-table-column prop="productUserName" label="生产人员" width="150" align="center" />
                            <el-table-column prop="reportQty" label="报工数" width="120" align="center" />
                            <el-table-column prop="unitName" label="单位" width="120" align="center" />
                            <el-table-column prop="goodQty" label="良品数" width="120" align="center" />
                            <el-table-column prop="noGoodQty" label="不良品数" width="200" align="center" />
                            <el-table-column prop="startDate" label="开始时间" width="200" align="center" />
                            <el-table-column prop="endDate" label="结束时间" width="200" align="center" />
                            <el-table-column prop="reoportDurationHour" label="报工时长(小时)" width="200" align="center" />
                            <el-table-column prop="reoportDurationMinute" label="报工时长(分钟)" width="200" align="center" />
                            <el-table-column prop="reportTime" label="报工时间" width="200" align="center" />
                            <el-table-column prop="createDate" label="创建时间" width="200" align="center" />
                            <el-table-column prop="creator" label="创建人" width="200" align="center" />
                            <el-table-column fixed="right" label="操作" min-width="100">
                                <template #default="scope">
                                    <el-row :gutter="4" style="row-gap: 12px;">
                                        <el-col :span="12">
                                            <el-button type="danger" size="small"
                                                @click="deleteWork(scope.row.reportWorkOrder_Id)">删除</el-button>
                                        </el-col>
                                    </el-row>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <div class="demo-pagination-block table-pagination"
                        style="display: flex; justify-content: flex-end;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalReportCount" @current-change="handleCurrentChange"
                            @size-change="handleSizeChange" />
                    </div>

                </div>

                <!-- 报工明细弹窗 -->
                <el-dialog v-model="detailDialogVisible" class="fixed-size-dialog" width="80%"
                    :before-close="handleClose">
                    <!-- 自定义标题 -->
                    <template #title>
                        <div style="display: flex; flex-direction: column;">
                            <span style="font-size: 20px; font-weight: bold;">报工明细</span>
                        </div>
                    </template>

                    <div class="dialog-body">
                        <div class="form-section">
                            <!-- 上部分表单 -->
                            <el-form :model="orderInfodetail[0]" label-width="120px" class="order-detail-form"
                                label-position="right">
                                <el-row :gutter="20">
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工单编号:">
                                            <el-input v-model="orderInfodetail[0].workOrder_Id" disabled />
                                        </el-form-item>
                                    </el-col> -->
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工单编号:">
                                            <el-select v-model="orderInfodetail[0].inventoryName" clearable
                                                collapse-tags-tooltip placeholder="请选择存货" style="width: 100%">
                                                <el-option v-for="emp in inventoryOptions" :key="emp.id"
                                                    :label="emp.inventoryName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col> -->

                                    <el-col :span="8">
                                        <el-form-item label="工单:">
                                            <!-- <el-input v-model="orderInfodetail[0].inventoryName" disabled /> -->
                                            <el-input :value="orderInfodetail[0].workOrderCode + ' | ' + orderInfodetail[0].inventoryName" disabled />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="工序:">
                                            <el-input v-model="orderInfodetail[0].processName" disabled />
                                        </el-form-item>
                                    </el-col>
                                    
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工序名称:">
                                            <el-select v-model="orderInfodetail[0].processName" clearable
                                                collapse-tags-tooltip placeholder="请选择工序" style="width: 100%">
                                                <el-option v-for="emp in processOptions" :key="emp.id"
                                                    :label="emp.processName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col> -->
                                    <el-col :span="8">
                                        <el-form-item label="存货:">
                                            <el-input v-model="orderInfodetail[0].inventoryName" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="存货编号:">
                                            <el-input v-model="orderInfodetail[0].inventoryCode" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="产品规格:">
                                            <el-input v-model="orderInfodetail[0].specificationModel" disabled />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="报工数">
                                            <el-input-number v-model="orderInfodetail[0].reportQty" :min="1"
                                                style="width:100%;"  />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="生产人员">
                                            <el-input v-model="detailInfo.productUserName" :min="1"
                                                style="width:100%;" disabled />
                                        </el-form-item>
                                    </el-col>

                                    <!-- <el-col :span="8">
                                        <el-form-item label="生产人员:">
                                            <el-select v-model="orderInfodetail[0].DistributionList" multiple clearable
                                                collapse-tags-tooltip placeholder="请选择生产人员" style="width: 100%">
                                                <el-option v-for="emp in employeeOptions" :key="emp.id"
                                                    :label="emp.employeesName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col> -->
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工序状态:">
                                            <el-input v-model="orderInfodetail[0].status" disabled />
                                        </el-form-item>
                                    </el-col> -->

                                    <!-- <el-col :span="8">
                                        <el-form-item label="单位:">
                                            <el-select v-model="orderInfodetail[0].unitName" clearable
                                                collapse-tags-tooltip placeholder=orderInfodetail[0].unitName
                                                style="width: 100%">
                                                <el-option v-for="emp in unitOptions" :key="emp.id"
                                                    :label="emp.unitName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col> -->

                                    <el-col :span="8">
                                        <el-form-item label="单位:">
                                            <el-input-number v-model="orderInfodetail[0].unitName" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="良品数:">
                                            <el-input-number v-model="orderInfodetail[0].goodQty" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="不良品数:">
                                            <el-input-number v-model="orderInfodetail[0].noGoodQty" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工序进度:">
                                            <el-input v-model="orderInfodetail[0].processProgress" disabled />
                                        </el-form-item>
                                    </el-col> -->
                                    <el-col :span="8">
                                        <el-form-item label="开始时间:">
                                            <el-date-picker v-model="orderInfodetail[0].startDate" type="datetime"
                                                placeholder=orderInfodetail[0].startDate style="width:100%;" />
                                            <!-- <el-input v-model="orderInfodetail.planStartDate"  /> -->
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="结束时间:">
                                            <el-date-picker v-model="orderInfodetail[0].endDate" type="datetime"
                                                placeholder=orderInfodetail[0].endDate style="width:100%;" />
                                            <!-- <el-input v-model="orderInfodetail.planStartDate"  /> -->
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="报工时长(小时):">
                                            <el-input-number v-model="orderInfodetail[0].reoportDurationHour" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="报工时长(分钟):">
                                            <el-input-number v-model="orderInfodetail[0].reoportDurationMinute" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="班组名称:">
                                            <el-input v-model="detailInfo.teamName" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="设备名称:">
                                            <el-input v-model="detailInfo.vendName" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="标准工时">
                                            <el-input-number
                                                v-model.trim="detailInfo.manHour"
                                                :min="0"
                                                :precision="2"
                                                style="width: 100%;"
                                                disabled
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24">
                                        <el-form-item label="备注">
                                            <el-input
                                                v-model="detailInfo.remark"
                                                placeholder="请输入备注"
                                                type="textarea"
                                                maxlength="200"
                                                show-word-limit
                                                disabled
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="达标率:">
                                            <el-input v-model="orderInfodetail[0].rateStandard" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="标准效率:">
                                            <el-input v-model="orderInfodetail[0].standardProgress" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="实际效率:">
                                            <el-input v-model="orderInfodetail[0].actualProgress" />
                                        </el-form-item>
                                    </el-col> -->
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                    <!-- <div class="form-section">
                        <div style="display: flex; flex-direction: column;">
                            <span style="font-size: 20px; font-weight: bold;">绩效信息</span>
                            <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>
                        </div>
                        绩效信息 
                        <el-form :model="orderInfodetail[0]" label-width="120px" class="order-detail-form"
                            label-position="right">
                            <el-row :gutter="20">
                                <el-col :span="8">
                                    <el-form-item label="计价方式:">
                                        <el-input v-model="orderInfodetail[0].workOrder_Id" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="工资单价:">
                                        <el-input v-model="orderInfodetail[0].inventoryName" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="应奖金额:">
                                        <el-input v-model="orderInfodetail[0].productStandard" disabled />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="8">
                                    <el-form-item label="应罚金额:">
                                        <el-input v-model="orderInfodetail[0].inventoryCode" disabled />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                    </div> -->

                    <!-- 分割线 -->
                    <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                    <!-- 下部分：订单明细表格 -->
                    <div class="table-section">
                        <el-table :data="orderInfodetail" style="width: 100%;" stripe border>
                            <el-table-column type="selection" width="55" />
                            <span>{{ orderInfodetail.value }}</span>
                            <!-- <el-table-column prop="processName" label="工序名称" width="230">
                                <template #default="scope">
                                    <span v-if="scope.row.processName">
                                        {{ scope.row.processName }}
                                    </span>
                                    <span v-else style="color: red; font-weight: bold;">
                                        null
                                    </span>
                                </template> 
                            </el-table-column>
                            <el-table-column prop="processCode" label="工序编号" width="200" /> -->
                            <el-table-column prop="defectItemName" label="不良品项列表" width="300" />
                            <el-table-column prop="qty" label="数量" width="150" />
                            <!-- <el-table-column prop="submitWorkLimit" label="报工权限" width="200">
                                <template #default="scope">
                                    <span>
                                        {{ scope.row.submitWorkMatch === 1 ? '所有人' : scope.row.submitWorkLimit }}
                                    </span>
                                </template>
                            </el-table-column> -->
                            <el-table-column prop="prL_CreateDate" label="创建时间" width="250" />
                            <el-table-column prop="prL_Creator" label="创建人" width="150" />
                            <el-table-column prop="prL_Modifier" label="修改人" width="150" />
                            <el-table-column prop="prL_ModifyDate" label="修改时间" width="280" />
                        </el-table>
                    </div>

                    <template #footer>
                        <el-button @click="detailDialogVisible = false">关闭</el-button>
                    </template>
                </el-dialog>

                <!-- 新增报工单弹窗 -->
                <el-dialog v-model="insertDialogVisiable" width="80%" :before-close="handleInsertClose">
                    <!-- 标题栏 -->
                    <template #title>
                        <div sttle="dispaly: flex; flex-direction: column;">
                            <span style="font-size: 20px; font-weight: bold;">新增报工单</span>
                            <div style="margin-top:20px; border-bottom: 1px solid #dcdfe6;"></div>
                        </div>
                    </template>
                    <!-- 上半部分表单 -->
                    <div class="dialog-body">
                        <div class="form-section">
                            <el-form :model="insertForm" label-width="120px" class="order-detail-form"
                                label-position="right">
                                <el-row :gutter="20">

                                    <el-col :span="8">
                                        <el-form-item label="工单:">
                                            <el-select v-model="insertForm.workOrder_Id" clearable placeholder="请选择工单"
                                                style="width: 100%" @change="handleInventoryChange">
                                                <el-option v-for="emp in WorkOptions" :key="emp.workOrder_Id"
                                                    :label="`${emp.workOrderCode} || ${emp.inventoryName}`"
                                                    :value="emp.workOrder_Id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>


                                    <el-col :span="8">
                                        <el-form-item label="工序名称:">
                                            <el-select v-model="insertForm.process_Id" clearable collapse-tags-tooltip
                                                placeholder="请选择工序" style="width: 100%" :disabled="!insertForm.workOrder_Id" @change="handleProcessChange">
                                                <el-option v-for="emp in processOptions" :key="emp.process_Id"
                                                    :label="emp.processName" :value="emp.process_Id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>

                                    <!-- 工序 -->
                                    <!-- <el-col :span="8">
                                        <el-form-item label="工序">
                                            <el-input v-model="inventory.processName" disabled />
                                        </el-form-item>
                                    </el-col> -->



                                    <!-- 存货 -->
                                    <el-col :span="8">
                                        <el-form-item label="存货">
                                            <el-input v-model="inventory.inventoryName" disabled />
                                        </el-form-item>
                                    </el-col>

                                    <!-- 存货编号 -->
                                    <el-col :span="8">
                                        <el-form-item label="存货编号">
                                            <el-input v-model="inventory.inventoryCode" disabled />
                                        </el-form-item>
                                    </el-col>

                                    <!-- 产品规格 -->
                                    <el-col :span="8">
                                        <el-form-item label="产品规格">
                                            <el-input v-model="inventory.specificationModel" disabled />
                                        </el-form-item>
                                    </el-col>


                                    <el-col :span="8">
                                        <el-form-item label="报工数">
                                            <el-input-number v-model="insertForm.reportQty" :min="1"
                                                style="width:100%;" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="生产人员:">
                                            <el-select v-model="insertForm.distributionList" clearable
                                                placeholder="请选择生产人员" style="width: 100%">
                                                <el-option v-for="emp in employeeOptions" :key="emp.id"
                                                    :label="emp.employeesName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>

                                    <!-- <el-col :span="8">
                                        <el-form-item label="单位:">
                                            <el-select v-model="insertForm.unitName" clearable collapse-tags-tooltip
                                                placeholder="请选择单位" style="width: 100%">
                                                <el-option v-for="emp in unitOptions" :key="emp.id"
                                                    :label="emp.unitName" :value="emp.id" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col> -->
                                    
                                    <!-- 单位 -->
                                    <el-col :span="8">
                                        <el-form-item label="单位">
                                            <el-input v-model="inventory.unitName" disabled />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="良品数">
                                            <el-input-number v-model="insertForm.goodQty" :min="0" style="width:100%;" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="不良品数">
                                            <el-input-number v-model="insertForm.noGoodQty" :min="0" style="width:100%;" />
                                        </el-form-item>
                                    </el-col>

                                    <!-- <el-col :span="8">
                                        <el-form-item label="工序进度">
                                            <el-input v-model="insertForm.inventoryName" disabled />
                                        </el-form-item>
                                    </el-col> -->

                                    <el-col :span="8">
                                        <el-form-item label="开始时间">
                                            <el-date-picker v-model="insertForm.planStartDate" type="datetime"
                                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="选择开始时间" style="width:100%;" @change="handleTimeChange('start')"/>
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="8">
                                        <el-form-item label="结束时间">
                                            <el-date-picker v-model="insertForm.planEndDate" type="datetime"
                                                format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss"
                                                placeholder="选择结束时间" style="width:100%;" @change="handleTimeChange('end')"/>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="报工时长(小时)">
                                            <el-input-number v-model="insertForm.reoportDurationHour" :min="0"
                                                style="width:100%;" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="报工时长(分钟)">
                                            <el-input-number v-model="insertForm.reoportDurationMinute" :min="0"
                                                style="width:100%;" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <!-- 报工可用数 -->
                                     <el-col :span="8">
                                        <el-form-item label="报工可用数">
                                            <el-input v-model="reportAvailableQuantity" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="班组名称">
                                            <el-select v-model="insertForm.teamId" clearable collapse-tags-tooltip
                                                placeholder="请选择班组" style="width: 100%">
                                                <el-option v-for="emp in teamOptions" :key="emp.teamId"
                                                    :label="emp.teamName" :value="emp.teamId" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="设备名称">
                                            <el-select v-model="insertForm.vendId" clearable collapse-tags-tooltip
                                                placeholder="请选择设备" style="width: 100%">
                                                <el-option v-for="emp in equipmentOptions" :key="emp.vendId"
                                                    :label="emp.vendName" :value="emp.vendId" />
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="标准工时">
                                            <el-input-number
                                                v-model.trim="insertForm.manHour"
                                                :min="0"
                                                :precision="2"
                                                placeholder="请输入标准工时"
                                                style="width: 100%;"
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="24">
                                        <el-form-item label="备注">
                                            <el-input
                                                v-model="insertForm.remark"
                                                placeholder="请输入备注"
                                                type="textarea"
                                                maxlength="200"
                                                show-word-limit
                                            />
                                        </el-form-item>
                                    </el-col>
                                    <!-- <el-col :span="8">
                                        <el-form-item label="达标率:">
                                            <el-input v-model="insertForm.rateStandard" disabled />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="标准效率:">
                                            <el-input v-model="insertForm.standardProgress" />
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="8">
                                        <el-form-item label="实际效率:">
                                            <el-input v-model="insertForm.actualProgress" />
                                        </el-form-item>
                                    </el-col> -->

                                    <!-- 绩效信息  -->
                                    <!-- <el-col :span="24">
                                        <el-form-item label="计价方式">
                                            <el-input v-model="insertForm.remark" type="textarea" placeholder="填写备注"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="24">
                                        <el-form-item label="工资单价">
                                            <el-input v-model="insertForm.remark" type="textarea" placeholder="填写备注"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="24">
                                        <el-form-item label="应奖金额">
                                            <el-input v-model="insertForm.remark" type="textarea" placeholder="填写备注"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col>

                                    <el-col :span="24">
                                        <el-form-item label="应罚金额">
                                            <el-input v-model="insertForm.remark" type="textarea" placeholder="填写备注"
                                                style="width: 100%" />
                                        </el-form-item>
                                    </el-col> -->

                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <!-- 分割线 -->
                    <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                    <!-- 下半部分：可新增不良品项的表格 -->
                    <div class="table-section">
                        <el-button type="primary" @click="addRow" style="margin-bottom: 10px;">新增不良品项</el-button>
                        <el-table :data="insertTableData" style="width: 100%;" border stripe>

                            <el-table-column type="index" label="序号" width="50" />

                            <!-- <el-table-column prop="process_Id" label="工序" width="150">
                                <template #default="scope">
                                    <el-input v-model="scope.row.processName" readonly
                                        @click="openProcessDialog(scope.row), loadingProcessData()"
                                        placeholder="选择工序" />
                                </template>
                            </el-table-column> -->
                            <el-table-column label="不良品项:" width="250">
                                <template #default="scope">
                                    <el-select v-model="scope.row.defectItem_Id" clearable collapse-tags-tooltip
                                        placeholder="请选择不良品项">
                                        <el-option v-for="emp in defectItemOptions" :key="emp.defectItem_Id"
                                            :label="emp.defectItemName" :value="emp.defectItem_Id" @click="defectItemChange(emp,scope.$index)" />
                                    </el-select>
                                    <!-- <span>{{ scope.row.defectItem_Id }}</span> -->
                                </template>
                            </el-table-column>


                            <el-table-column prop="qty" label="数量" width="200">
                                <template #default="scope">
                                    <el-input-number v-model="scope.row.qty" :min="0" />
                                </template>
                            </el-table-column>

                            <el-table-column prop="createDate" label="创建时间" width="250">
                                <template #default="scope">
                                    <el-date-picker v-model="scope.row.createDate" disabled />
                                </template>
                            </el-table-column>

                            <el-table-column prop="creator" label="创建人" width="150">
                                <template #default="scope">
                                    <el-input v-model="scope.row.creator" disabled />
                                </template>
                            </el-table-column>

                            <el-table-column prop="modifier" label="修改人" width="150">
                                <template #default="scope">
                                    <el-input v-model="scope.row.modifier" disabled />
                                </template>
                            </el-table-column>

                            <el-table-column prop="modifyDate" label="修改时间" width="180">
                                <template #default="scope">
                                    <el-date-picker v-model="scope.row.modifyDate" disabled />
                                </template>
                            </el-table-column>

                            <el-table-column label="操作" width="100">
                                <template #default="scope">
                                    <el-button type="danger" @click="removeRow(scope.$index)"
                                        size="small">删除</el-button>
                                </template>
                            </el-table-column>

                        </el-table>
                    </div>

                    <template #footer>
                        <el-button @click="handleInsertClose()">取消</el-button>
                        <el-button type="primary" @click="saveInsert()">保存</el-button>
                    </template>
                </el-dialog>

                <!-- 存货选择弹窗 -->
                <el-dialog v-model="inventoryDialogVisible" width="1200px" :close-on-click-modal="false"
                    :destroy-on-close="true" top="5vh" class="fixed-inventory-dialog">
                    <template #title>
                        <span style="font-weight: bold;">选择存货</span>
                    </template>

                    <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                        <el-input v-model="inventorySearchData.Code" placeholder="存货编号或编码" clearable
                            style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                            @keyup.enter.native="handleSearch" />

                        <el-button type="primary" @click="handleSearch"
                            style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                            搜索
                        </el-button>
                    </div>

                    <!-- 表格滚动容器 -->
                    <div class="table-scroll-wrapper">
                        <el-table :data="inventoryOptions" stripe border style="width: 100%;"
                            @selection-change="handleSelectionChange">
                            <!-- 序号列 -->
                            <el-table-column type="index" width="50" />
                            <!-- 选择列 -->
                            <el-table-column type="selection" width="50"
                                :selectable="(row, index) => !!row.processLineName" />
                            <el-table-column prop="inventoryCode" label="产品编号" width="250" />
                            <el-table-column prop="inventoryName" label="产品名称" width="220" />
                            <el-table-column prop="unitName" label="单位" width="120" />
                            <el-table-column prop="specificationModel" label="产品规格" width="290" />
                            <el-table-column prop="processLineName" label="工艺路线" width="180" />
                        </el-table>
                    </div>

                    <!-- 分页部分 -->
                    <div class="demo-pagination-block"
                        style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalCount" @current-change="handleCurrentChangeInventory"
                            @size-change="handleSizeChangeInventory" />
                    </div>

                    <!-- 底部按钮 -->
                    <template #footer>
                        <div style="text-align: right;">
                            <el-button @click="inventoryDialogVisible = false">取消</el-button>
                            <el-button type="primary" @click="confirmInventory">确定</el-button>
                        </div>
                    </template>
                </el-dialog>

                <!-- 工序选择弹窗 -->
                <el-dialog v-model="processDialogVisible" width="1200px" :close-on-click-modal="false"
                    :destroy-on-close="true" top="5vh" class="fixed-inventory-dialog">
                    <template #title>
                        <span style="font-weight: bold;">选择工序</span>
                    </template>

                    <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                        <el-input v-model="processSearchData.processCode" placeholder="工序编号或编码" clearable
                            style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                            @keyup.enter.native="handleProcessSearch" />

                        <el-button type="primary" @click="handleProcessSearch"
                            style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                            搜索
                        </el-button>
                    </div>

                    <!-- 表格滚动容器 -->
                    <div class="table-scroll-wrapper">
                        <el-table :data="processOptions" stripe border style="width: 100%;"
                            @selection-change="handleProcessSelectionChange">
                            <!-- 序号列 -->
                            <el-table-column type="index" width="50" />
                            <!-- 选择列 -->
                            <el-table-column type="selection" width="50" />
                            <el-table-column prop="processCode" label="工序编号" width="200" />
                            <el-table-column prop="processName" label="工序名称" width="200" />
                            <el-table-column prop="submitWorkLimit" label="报工权限" width="150" />
                            <el-table-column prop="submitWorkMatch" label="报工权限比" width="200" />
                            <el-table-column prop="defectItemName" label="不良品项列表" width="300" />
                            <!-- <el-table-column prop="defectItemName" label="不良品项列表" width="300">
                                <template #default="scope">
                                    {{ mergeDefectItems(scope.row.processCode) }}
                                </template>
                            </el-table-column> -->

                        </el-table>
                    </div>

                    <!-- 分页部分 -->
                    <div class="demo-pagination-block"
                        style="display: flex; justify-content: flex-end; margin-top: 20px;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalCount" @current-change="handleCurrentChangeProcess"
                            @size-change="handleSizeChangeProcess" />
                    </div>

                    <!-- 底部按钮 -->
                    <template #footer>
                        <div style="text-align: right;">
                            <el-button @click="handleInsertClose()">取消</el-button>
                            <el-button type="primary" @click="confirmProcess">确定</el-button>
                        </div>
                    </template>
                </el-dialog>

            </div>
        </el-container>
    </div>
</template>

<script setup>
import { ref, watch, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
    WorkOrderSearchList,
    WorkOrderSearchListDetail,
    getInventory,
    getProcess,
    getProcessCode,
    addProcess,
    changeWorkStatus,
    GetReportWork,
    ReportSearchListDetail,
    getUnit,
    getEmployee,
    getDefectItem,
    deleteReportWork,
    addReportWork,
    selectInventory,
    getProcessInfoByWorkOrderId,
    getReportAvailableQuantity,
    getTeamInfoList,
    getVendInfoList
} from '../../extension/V2/ReportWork'

// 搜索条件模型
const searchModel = ref({ ProcessName: '' })

// 表格数据与分页数据
const detailTableData = ref([]) // 订单展示明细模型
const detailDialogVisible = ref(false)

const radio1 = ref('1')

let loading = ref(false)

const totalCount = ref(0)
const totalReportCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)

const orderInfodetail = ref([{
    workOrderCode: '',
    inventoryName: '',
    productStandard: '',
    inventoryCode: '',
    unitName: '',
    planStartDate: '',
    planEndDate: '',
    planQty: '',
    status: '',
    remark: ''
}])


const statusText = (status) => {
    switch (status) {
        case 1: return '未开始';
        case 2: return '进行中';
        case 3: return '已完成';
        case 4: return '已撤回';
        case 5: return '已取消';
        default: return '';
    }
}

const statusColor = (status) => {
    switch (status) {
        case 1: return 'green';
        case 2: return '#e6a23c'; // 警告色
        case 3: return 'red';
        case 4: return 'gray';
        case 5: return 'gray';
        default: return 'black';
    }
}

// 获取当前分页+搜索参数
const getParams = () => ({
    ProcessName: searchModel.value.ProcessName,
    page: currentPage.value,
    rows: pageSize.value,
    sort: 'desc',
    order: 'CreateDate'
})

// 分页页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page
    Search()
}

// 分页每页条数变化
const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    Search()
}

// 查询方法 (分页变化,自动渲染)
const Search = async () => {
    loading = true
    const params = getParams()
    console.log("已执行params：", params)

    try {
        const result = await GetReportWork(params)
        console.log("已执行result：", result)
        console.log("已执行result.status：", result.status)
        if (result.status === 0) {
            detailTableData.value = result.rows || []
            totalReportCount.value = result.total || 0
            loading = false
        } else {
            detailTableData.value = []
            totalReportCount.value = 0
            ElMessage.error(result.msg || '查询失败')
        }
    } catch (error) {
        console.error('查询异常:', error)
    }
}

// 搜索按钮
const SearchList = async () => {
    const params = getParams()
    console.log("已执行params：", params)
    const result = await GetReportWork(params)
    if (result.status === 0) {
        detailTableData.value = result.rows
        totalCount.value = result.total
    } else {
        detailTableData.value = []
        totalCount.value = 0
        ElMessage.error(result.msg || '查询失败')
    }
}


// 报工明细部分
const showWorkOrderDetailData = async (ReportWorkOrder_Id) => {
    console.log("已执行workOrder_Id：", ReportWorkOrder_Id)
    const result = await ReportSearchListDetail(ReportWorkOrder_Id)
    orderInfodetail.value = result.rows || []
    console.log("orderInfodetail:", orderInfodetail.value)
}

const detailInfo = ref({})

const showWorkOrderDetail = (id, val) => {
    detailInfo.value = JSON.parse(JSON.stringify(val))
    detailDialogVisible.value = true
    showWorkOrderDetailData(id)
    console.log("已执行row.ReportWorkOrder_Id", id)
}

// 弹窗滚动控制
watch(() => detailDialogVisible.value, (val) => {
    document.body.style.overflow = val ? 'hidden' : ''
})


// 新增工单方法 ----

const insertDialogVisiable = ref(false) //定义新增弹窗

// 定义新增工单模型
const insertForm = ref({
    workOrderCode: '',
    inventoryName: '',
    inventoryId: '',
    planStartDate: '',
    planEndDate: '',
    planQty: 0,
    reportTime: '',
    remark: '',
    inventoryCode: '',
    process_Id: '',
    workOrder_Id: '',
    defectItem_Id: '',
    defectItems: [],
    teamId: '',
    vendId: '',
    manHour: null,
    remark: '',

    productionWorkOrderDetails: [],
})

//定义选择存货弹窗
const inventoryDialogVisible = ref(false)

// 关闭时清空数据
// const handleInsertClose = () => {
//     Object.assign(insertForm.value, {
//         workOrderCode: '',
//         inventoryName: '',
//         inventory_Id: '',
//         planStartDate: '',
//         planEndDate: '',
//         planQty: 0,
//         reportTime: '',
//         remark: '',
//     })
//     // insertTableData.value = []
//     insertDialogVisiable.value = false
// }

// 定义 点击打开新增弹窗
const InsertData = () => {
    insertDialogVisiable.value = true
    GetProcessCode()
    loadingWorkData()
    // 获取班组信息
    loadingTeamData()
    // 获取设备信息
    loadingEquipmentData()
}

// 定义用户输入的搜索内容
const inventorySearchData = reactive({
    Code: ''
})

// 定义 存货分页
const inventoryCurrentPage = ref(1)
const inventoryPageSize = ref(15)
const inventoryTotal = ref(0)

// 当前正在编辑的订单行
const currentRow = ref(null)

// // 定义用户输入的搜索内容
// const inventorySearchData = reactive({
//     Code: ''
// })

// 获取存货搜索参数
const getProductParams = () => {
    const wheresArr = []
    if (inventorySearchData.Code) {
        wheresArr.push({
            name: 'workOrderCode',       // 搜索字段名
            value: String(inventorySearchData.Code || ''),
            displayType: 'like'          // 模糊匹配
        })
    }

    return {
        page: inventoryCurrentPage.value,
        rows: inventoryPageSize.value,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify(wheresArr)  // 转为 JSON 字符串
    }
}

// 打开弹窗并加载存货数据
const openInventoryDialog = async (row) => {
    currentRow.value = row
    inventoryDialogVisible.value = true
    inventoryCurrentPage.value = 1   // 打开时回到第一页
}

// 分页页码变化
const handleCurrentChangeInventory = (page) => {
    inventoryCurrentPage.value = page
    loadingInventoryData()
    // Search()
}

// 分页每页条数变化
const handleSizeChangeInventory = (rows) => {
    console.log("页大小变化:", rows)
    inventoryPageSize.value = rows
    inventoryCurrentPage.value = 1
    loadingInventoryData()
    console.log("页大小变化pageSize.value:", pageSize.value)
}

// 定义存货响应数据
const inventoryOptions = ref([])
//加载存货数据
const loadingInventoryData = async () => {
    try {
        const params = getProductParams()
        console.log("数据加载getInventory()")
        const res = await getInventory(params)
        console.log("数据加载成功getInventory（）", res)
        inventoryOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

// 定义工单响应数据
const WorkOptions = ref([])
//加载存货数据
const loadingWorkData = async () => {
    try {
        const params = getProductParams()
        console.log("数据加载getInventory()")
        const res = await WorkOrderSearchList(params)
        console.log("数据加载成功getInventory（）", res)
        WorkOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

// 定义班组响应数据
const teamOptions = ref([])
//加载存货数据
const loadingTeamData = async () => {
    try {
        const params = {
            TeamName: "", // 班组名称
            rows: 10000,
            page: 1,
        }
        const res = await getTeamInfoList(params)
        if (res.status === 0) {
            teamOptions.value = res.rows || []
        }
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

// 定义设备响应数据
const equipmentOptions = ref([])
//加载存货数据
const loadingEquipmentData = async () => {
    try {
        const params = {
            VendName: "", // 设备名称
            rows: 10000,
            page: 1,
        }
        const res = await getVendInfoList(params)
        if (res.status === 0) {
            equipmentOptions.value = res.rows || []
        }
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

// 定义存货响应数据
const unitOptions = ref([])
//加载单位数据
const loadingUnitData = async () => {
    try {
        const params = getProductParams()
        console.log("数据加载getInventory()")
        const res = await getUnit(params)
        console.log("数据加载成功getInventory（）", res)
        unitOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

const defectItemOptions = ref([])

// 获取不良品数据
const loadDefectItemData = async () => {
    try {
        console.log("111员工数据加载")
        const result = await getDefectItem()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            defectItemOptions.value = result.rows || []
            console.log("defectItemOptions:", defectItemOptions.value)
        } else {
            ElMessage.error(result.msg || '获取不良品数据失败')
        }
    } catch (err) {
        console.error('获取不良品数据异常:', err)
    }
}

//  选择存货弹窗搜索功能
const handleSearch = () => {
    // 调用加载方法
    currentPage.value = 1   // 搜索时回到第一页
    loadingInventoryData()
}

// 当前选中的存货（单选）
const selectedInventory = ref([])
// 表格勾选事件（这里用单选，所以取第一条）
const handleSelectionChange = (val) => {
    selectedInventory.value = val
}

// 确认选择
const confirmInventory = () => {
    if (!selectedInventory.value || selectedInventory.value.length === 0) {
        ElMessage.warning("请选择至少一条存货")
        return
    }

    // 取第一个选中的存货
    const first = selectedInventory.value[0]
    console.log("确认选择:", first)

    // 注意：后端查出来是 id，这里转成新增接口需要的 inventory_Id
    insertForm.value.inventoryName = first.inventoryName
    insertForm.value.inventory_Id = first.id   // 用后端返回的 id

    // 关闭弹窗并清空已选
    inventoryDialogVisible.value = false
    selectedInventory.value = []
}

// 新增下半部分表格数据
const insertTableData = ref([])

// 添加新一行工序
const addRow = () => {
    insertTableData.value.push({
        process_Id: null,           // 工序
        submitWorkMatch: 0,         // 报工数配比，默认0
        defectItemName: '',             // 不良品项
        planStartDate: '',          // 计划开始时间
        planEndDate: '',            // 计划结束时间
        planQty: '',                 // 计划数，默认1
        inventoryName: '',          // 产品名称--存货
        inventoryId: '',          // 存货ID
        inventoryCode: '',          // 产品编号--存货
        specificationModel: '',     // 产品规格--存货
        FinishedProduct: 0,         // 完成数，默认0
        CreateDate: '',             // 创建时间
        CreateID: '',               // 创建人id
        Creator: '',                // 创建人
        Modifier: '',               // 修改人
        ModifyDate: '',             // 修改时间
        defectItem_Id: [],
        qty: ''
    })
}
// 字段监听，实现计划开始，结束时间，计划数上下部分数据同步
watch(
    () => insertForm.value.planStartDate,
    (newVal) => {
        insertTableData.value.forEach(row => {
            row.planStartDate = newVal
        })
    }
)

watch(
    () => insertForm.value.planEndDate,
    (newVal) => {
        insertTableData.value.forEach(row => {
            row.planEndDate = newVal
        })
    }
)

watch(
    () => insertForm.value.planQty,
    (newVal) => {
        insertTableData.value.forEach(row => {
            row.planQty = newVal
        })
    }
)

// 定义新增工序模型
const processForm = ref({
    workOrderCode: '',
    inventoryName: '',
    inventory_Id: null,
    planStartDate: '',
    planEndDate: '',
    planQty: 0,
    reportTime: '',
    remark: '',
    productionWorkOrderDetails: []
})

// 当前正在编辑的工序行
const currentProcessRow = ref(null)
const currentProcessPage = ref(1)

//定义选择工序弹窗
const processDialogVisible = ref(false)
// 打开弹窗并加载工序数据数据
const openProcessDialog = async (row) => {
    currentProcessRow.value = row
    processDialogVisible.value = true
    currentProcessPage.value = 1   // 打开时回到第一页
}

// 定义用户输入的搜索内容 ---工序
const processSearchData = reactive({
    processCode: ''
})

// 选择工序搜索功能
const handleProcessSearch = () => {
    // 调用加载方法
    currentPage.value = 1   // 搜索时回到第一页
    loadingProcessData()
}

// // 定义用户输入的搜索内容 --工序
// const processSearchData = reactive({
//     Code: ''
// })

// 获取工序搜索参数
const getProcessParams = () => {
    const wheresArr = []
    if (processSearchData.processCode) {
        wheresArr.push({
            name: 'processCode',       // 搜索字段名
            value: String(processSearchData.processCode || ''),
            displayType: 'like'          // 模糊匹配
        })
    }

    return {
        page: processCurrentPage.value,
        rows: processPageSize.value,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify(wheresArr)  // 转为 JSON 字符串
    }
}
// 定义工序响应数据
const processOptions = ref([])
// 加载工序数据
const loadingProcessData = async () => {
    try {
        const params = getProcessParams()
        console.log("数据加载params", params)
        const res = await getProcess(params)
        console.log("数据加载成功getProcess（）", res)
        processOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

// 定义员工响应数据
const employeeOptions = ref([])
// 加载工序数据
const loadingEmployeeData = async () => {
    try {
        const params = getProcessParams()
        console.log("数据加载params", params)
        const res = await getEmployee(params)
        console.log("数据加载成功getProcess（）", res)
        employeeOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

// 当前选中的工序（单选）
const selectedProcess = ref([])
// 表格勾选事件（这里用单选，所以取第一条）
const handleProcessSelectionChange = (val) => {
    selectedProcess.value = val
}

// 定义 工序分页
const processCurrentPage = ref(1)
const processPageSize = ref(15)
const prcessTotal = ref(0)

// 分页页码变化
const handleCurrentChangeProcess = (page) => {
    processCurrentPage.value = page
    loadingProcessData()
    // Search()
}

// 分页每页条数变化
const handleSizeChangeProcess = (rows) => {
    console.log("页大小变化:", rows)
    processPageSize.value = rows
    processCurrentPage.value = 1
    loadingProcessData()
    console.log("页大小变化pageSize.value:", processPageSize.value)
}

// 确认选择 --- 工序回显
// const confirmProcess = () => {
//   if (!currentProcessRow.value || !selectedProcess.value.length) return

//   const selected = selectedProcess.value[0]

//   // 按弹窗列字段回显
//   currentProcessRow.value.processCode = selected.processCode
//   currentProcessRow.value.processName = selected.processName
//   currentProcessRow.value.submitWorkLimit = selected.submitWorkLimit
//   currentProcessRow.value.submitWorkMatch = selected.submitWorkMatch
//   currentProcessRow.value.defectItem = selected.defectItem

//   // 关闭弹窗
//   processDialogVisible.value = false
// }

// // 用 Map 先把同工序的 defectItemName 合并
// const mergeDefectItems = (processCode) => {
//   // 找到同工序的所有行
//   const rows = processOptions.value.filter(item => item.processCode === processCode)

//   // 提取 defectItemName，去重
//   const defectSet = new Set()
//   rows.forEach(r => {
//     if (r.defectItemName) {
//       defectSet.add(r.defectItemName)
//     }
//   })

//   // 返回合并后的字符串
//   return Array.from(defectSet).join(' | ')
// }

// // 去重后的数组，供表格渲染
// const mergedProcessOptions = computed(() => {
//   const map = new Map()
//   processOptions.value.forEach(row => {
//     if (!map.has(row.processCode)) {
//       map.set(row.processCode, row)
//     }
//   })
//   return Array.from(map.values())
// })

// 删除行
const removeRow = (index) => {
    insertTableData.value.splice(index, 1)
}

// 确认选择 --- 工序回显
const confirmProcess = () => {
    if (!currentProcessRow.value || selectedProcess.value.length === 0) {
        ElMessage.warning("请选择至少一条工序")
        return
    }

    const first = selectedProcess.value[0]

    // 回显到当前行
    Object.assign(currentProcessRow.value, {
        processName: first.processName,
        processCode: first.processCode,           // 工序编号
        process_Id: first.process_Id,
        submitWorkLimit: first.submitWorkLimit,   // 报工权限
        submitWorkMatch: first.submitWorkMatch,
        defectItemName: first.defectItemName,
        planStartDate: insertForm.value.planStartDate,
        planEndDate: insertForm.value.planEndDate,
        planQty: insertForm.value.planQty
    })

    // 剩余选中工序新增行
    for (let i = 1; i < selectedProcess.value.length; i++) {
        const item = selectedProcess.value[i]
        insertTableData.value.push({
            processName: item.processName,
            processCode: item.processCode,
            process_Id: item.process_Id,
            inventoryId: item.inventoryId,
            submitWorkLimit: item.submitWorkLimit,
            submitWorkMatch: item.submitWorkMatch,
            defectItemName: item.defectItemName,
            planStartDate: item.planStartDate,
            planEndDate: item.planEndDate,
            planQty: item.planQty
        })
    }

    processDialogVisible.value = false
    selectedProcess.value = [] // 清空已选
}

// 自动获取生产计划单据编号
const GetProcessCode = async () => {
    try {
        const res = await getProcessCode()
        console.log("获取工单编号成功:", res)
        if (res && res.data) {
            insertForm.value.workOrderCode = res.data
            console.log("获取工单编号成功res.data:", res.data)
            console.log("获取工单编号成功insertForm.value.workOrderCode:", insertForm.value.workOrderCode)
        }
    } catch (err) {
        console.error('获取工单编号失败:', err)
        ElMessage.error('获取工单编号失败')
    }
}

//添加工单
// const saveInsert = async () => {
//     console.log("进入添加工单insertForm.value", insertForm.value)
//     try {
//         const res = await addProcessCode(insertForm.value)
//         console.log("添加工单成功:", res)
//         if (res && res.data) {
//             ElMessage.success('添加工单成功')
//             insertForm.value = {}
//             insertTableData.value = []
//             Search()
//         }
//     } catch (err) {
//         console.error('添加工单失败:', err)
//         ElMessage.error('添加工单失败')
//     }
// }

// 关闭时清空数据
const handleInsertClose = () => {

    insertDialogVisiable.value = false

    Object.assign(insertForm.value, {
        workOrderCode: '',
        planStartDate: '',
        planEndDate: '',
        planQty: '',
        reportTime: '',
        remark: '',
        inventory_Id: '',
        inventoryName: '',
        workOrder_Id:'',
        reportQty:'',
        goodQty: '',
        noGoodQty:'',
        reoportDurationMinute:'',
        reoportDurationHour:'',
        distributionList:'',
        process_Id: '',
        teamId: '',
        vendId: '',
        manHour: null,
        remark: '',

    })

    Object.assign(inventory.value, {
        inventoryName: '',
        inventoryCode: '',
        specificationModel: '',
        processName:'',
        unitName:''

    })
    insertTableData.value = []

    // 清空可用数
    reportAvailableQuantity.value = null
}

const inventory = ref({
    id: '',
    inventoryName: '',
    inventoryCode: '',
    specificationModel: '',
    processName:'',
    unitName: '',
    process_Id:'',
    unitId:''

})

// 报工可用数
const reportAvailableQuantity = ref(0)

const handleInventoryChange = async (selectedId) => {
    const selected = WorkOptions.value.find(emp => emp.workOrder_Id === selectedId)
    console.log('当前选中的工单：',selected);
    // 清空工序名称数据
    processOptions.value = []
    insertForm.value.process_Id = null
    // 清空报工可用数
    reportAvailableQuantity.value = 0
    if (selected) {
        // 点击工单后，重新获取工序名称，根据id获取
        try {
            const res = await getProcessInfoByWorkOrderId(selected.workOrder_Id)
            console.log("获取工序名称接口返回 res:", res)
            if (res.ok && res.data) {
                processOptions.value = res.data
            }
        } catch (err) {
            console.error("获取工序名称失败:", err)
        }

        try {
            console.log("获取存货接口参数 selected:", selected)
            const res = await selectInventory(selected.inventory_Id)
            console.log("获取存货接口返回 res:", res)

            if (res && res.rows) {
                const data = Array.isArray(res.rows) ? res.rows[0] : res.rows
                console.log("获取存货接口返回 inventory:", data)

                // 更新存货模型
                inventory.value = {
                    id: data.id || '',
                    inventoryName: data.inventoryName || '',
                    inventoryCode: data.inventoryCode || '',
                    specificationModel: data.specificationModel || '',
                    processName: data.processName || '',
                    unitName: data.unitName || '',
                    process_Id: data.process_Id || ''
                }
            }
            console.log("更新后的 inventory:", inventory.value)
        } catch (err) {
            console.error("获取存货失败:", err)
        }
    }
}

const handleProcessChange = async (selectedId) => {
    console.log(selectedId);
    // 获取报工可用数
    try {
        const res = await getReportAvailableQuantity({
            WordOrderId: insertForm.value.workOrder_Id,
            ProcessId: selectedId
        })
        console.log("获取报工可用数接口返回 res:", res)
        if (res.ok && res.data) {
            reportAvailableQuantity.value = res.data
        }
    } catch (err) {
        console.error("获取报工可用数失败:", err)
    }
}

const handleTimeChange = (type)=> {
    // 开始时间和结束时间是否填写完整
    if (!insertForm.value.planStartDate || !insertForm.value.planEndDate) {
        return
    }
    // 解析时间
    const duration = validateAndCalculateTime(insertForm.value.planStartDate, insertForm.value.planEndDate, type)
    console.log('时间---', duration)
    if(!duration.isValid) return ElMessage.error(duration.error)
    // 计算时长 分钟
    insertForm.value.reoportDurationHour = duration.duration.hours
    insertForm.value.reoportDurationMinute = duration.duration.minutes
}

const validateAndCalculateTime = (startTime, endTime, type) => {
    // 转换为 Date 对象
    const start = new Date(startTime)
    const end = new Date(endTime)
    // 验证时间有效性
    if (isNaN(start.getTime()) || isNaN(end.getTime())) {
        return {
            isValid: false,
            error: '时间格式不正确'
        }
    }
    // 验证开始时间不能超过结束时间
    if (start > end) {
        return {
            isValid: false,
            error: type === 'start' ? '开始时间不能超过结束时间' : '结束时间不能低于开始时间'
        }
    }
    // 判断时间是否相等
    if (start.getTime() === end.getTime()) {
      return {
        isValid: false,
        error: "开始时间和结束时间不能相同",
      };
    }
    // 计算时间差（毫秒）
    const diffMs = end - start
    // 转换为小时和分钟
    const totalMinutes = Math.floor(diffMs / (1000 * 60))
    const hours = Math.floor(totalMinutes / 60)
    const minutes = totalMinutes % 60
    return {
        isValid: true,
        duration: {
            hours,
            minutes,
            totalHours: (totalMinutes / 60).toFixed(2),
            totalMinutes,
            display: `${hours}小时${minutes}分钟`
        }
    }
}

// 添加报工单
const saveInsert = async () => {

    // 同步表格的不良品到 insertForm
    insertForm.value.defectItems = insertTableData.value.flatMap(row => {
        const ids = Array.isArray(row.defectItem_Id) ? row.defectItem_Id : [row.defectItem_Id].filter(Boolean)
        return ids.map(id => ({
            DefectItemId: id,
            Qty: row.qty || 0
        }))
    })

    console.log("保存前的 insertForm:", insertForm.value)

    // 工单
    if(!insertForm.value.workOrder_Id) return ElMessage.error("请选择工单")
    // 工序
    if(!insertForm.value.process_Id) return ElMessage.error("请选择工序")
    // 报工数
    if(!insertForm.value.reportQty) return ElMessage.error("请填写报工数")
    // 报工数不能大于报工可用数
    if(insertForm.value.reportQty > reportAvailableQuantity.value) return ElMessage.error("报工数不能大于报工可用数")
    // 良品数
    if(!insertForm.value.goodQty && insertForm.value.goodQty!==0) return ElMessage.error("请填写良品数")
    // 良品数不能大于报工数
    if (insertForm.value.goodQty > insertForm.value.reportQty) {
        ElMessage.error("良品数不能大于报工数");
        return;
    }
    // 不良品数
    if(!insertForm.value.noGoodQty && insertForm.value.noGoodQty!==0) return ElMessage.error("请填写不良品数")

    // 报工数=良品数+不良品数
    if (insertForm.value.goodQty + insertForm.value.noGoodQty != insertForm.value.reportQty) {
        ElMessage.error("良品数+不良品数不能大于报工数");
        return;
    }

    // 开始时间 结束时间
    if(!insertForm.value.planStartDate) return ElMessage.error("请填写开始时间")
    if(!insertForm.value.planEndDate) return ElMessage.error("请填写结束时间")
    const duration = validateAndCalculateTime(insertForm.value.planStartDate, insertForm.value.planEndDate, 'start')
    if(!duration.isValid) return ElMessage.error(duration.error)

    // 班组
    if(!insertForm.value.teamId){
        ElMessage.error("请选择班组")
        return
    }

    // 设备
    if(!insertForm.value.vendId){
        ElMessage.error("请选择设备")
        return
    }

    // 标准工时

    // 不良品数不为0时 才需要填写不良品项
    if(insertForm.value.noGoodQty) {
        if (insertForm.value.defectItems.length === 0) {
            ElMessage.error("请填写不良品项")
            return
        }

        if (
        insertForm.value.defectItems.some((row) => !row.DefectItemId) ||
        insertForm.value.defectItems.some((row) => !row.Qty)
        ) {
            ElMessage.error("请填写不良品项和数量");
            return;
        }
        // 不良品集合的数量加起来应该等于不良品数
        if (insertForm.value.noGoodQty !== insertForm.value.defectItems.map((item) => item.Qty).reduce((a, b) => a + b, 0)) {
            ElMessage.error("不良品项数量之和需要等于不良品数");
            return;
        }
    }

    try {
        // 构造请求参数
        const payload = {
            WorkOrder_Id: insertForm.value.workOrder_Id || 0,    // 工单Id
            Inventory_Id: inventory.value.id || 0,
            Unit_Id:inventory.value.unitId || 0,    // 存货Id
            Process_Id: insertForm.value.process_Id || 0,        // 工序Id
            ProcessStatus: insertForm.value.processStatus || 0,  // 工序状态
            ReportQty: insertForm.value.reportQty || 0,          // 报工数
            GoodQty: insertForm.value.goodQty || 0,              // 良品数
            NoGoodQty: insertForm.value.noGoodQty || 0,          // 不良品数
            StartDate: insertForm.value.planStartDate || null,         // 开始时间
            EndDate: insertForm.value.planEndDate || null,             // 结束时间
            ReoportDurationHour: insertForm.value.reoportDurationHour || 0,   // 报工时长-小时
            ReoportDurationMinute: insertForm.value.reoportDurationMinute || 0, // 报工时长-分钟
            StandardProgress: insertForm.value.standardProgress || null,   // 标准效率
            ActualProgress: insertForm.value.actualProgress || null,       // 实际效率
            RateStandard: insertForm.value.rateStandard || null,           // 达标率
            PriceType: insertForm.value.priceType || null,               // 计价方式
            UnitPrice: insertForm.value.unitPrice || null,               // 工资单价
            productUserId: insertForm.value.distributionList|| null,    // 生产人员ID
            teamId: insertForm.value.teamId, // 班组id
            vendId: insertForm.value.vendId,// 设备id
            manHour: insertForm.value.manHour || null, // 标准工时
            remark: insertForm.value.remark || '', // 备注

            DefectItems: insertForm.value.defectItems

            // defectItems: (insertForm.value.defectItems && insertForm.value.defectItems.length > 0)
            //     ? insertForm.value.defectItems.map(item => ({
            //         defectItemId: item.defectItem_Id, // 不良项Id
            //         qty: item.qty                    // 数量
            //     }))
            //     : []

        }
        console.log('测试参数 payload:', payload)

        // 基本校验

        // if (!payload.StartDate) {
        //     ElMessage.error("请填写开始时间")
        //     return
        // }
        // if (!payload.EndDate) {
        //     ElMessage.error("请填写结束时间")
        //     return
        // }

        // if (!payload.DefectItems.DefectItemId) {
        //     ElMessage.error("请填写不良品项")
        //     return
        // }
        // if (!payload.DefectItems.qty) {
        //     ElMessage.error("请填写数量")
        //     return
        // }



        console.log('请求参数 payload:', payload)

        //调用新增接口
        const result = await addReportWork(payload)
        console.log("接口返回 result:", result)

        if (result && result.ok === true) {
            ElMessage.success(
                (result && result.err && result.err.msg) || '新增工单成功'
            )
            Search()
            handleInsertClose()
        } else {
            ElMessage.error(
                (result && result.err && result.err.msg) || '新增工单失败'
            )
        }
    } catch (err) {
        console.error('保存异常:', err)
        ElMessage.error('保存异常')
    }
}

// 删除报工单
const deleteWork = async (id) => {

    try {
        const res = await deleteReportWork(id)

        console.log("删除工单接口返回 res:", res)
        if (res.item1 === true) {
            ElMessage.success('删除成功');
            Search();
        } else {
            ElMessage.error('删除失败：' + (res.item2.msg || "未知错误"));
        }
    } catch (err) {
        console.error('删除工单异常:', err)
        ElMessage.error('删除工单异常')
    }
}

const defectItemChange = (row, index) => {
    // 获取当前选择的值
    const selectedValue = row.defectItem_Id;
    if (!selectedValue) {
      return; // 如果清空了选择，不做处理
    }
    // 检查是否重复
    const isDuplicate = insertTableData.value.some((item, i) =>
      i !== index && item.defectItem_Id === selectedValue
    );
    if (isDuplicate) {
      // 提示用户并清空选择
      ElMessage.error('该不良品项已被选择，请选择其他项');
      insertTableData.value[index].defectItem_Id = null; // 清空选择
      return;
    }
}




// 初始化
Search()
loadingInventoryData()
loadingProcessData()
loadingUnitData()
loadingEmployeeData()
loadDefectItemData()
// loadingWorkData()

//修改工单状态
const changeWork = async (workOrder_Id, status) => {
    try {
        const params = {
            WorkOrder_Id: workOrder_Id,
            Status: status
        }
        const res = await changeWorkStatus(params)

        if (res && res.data) {
            ElMessage.success('工单状态更新成功')
            Search()
        } else {
            ElMessage.error('工单状态更新失败')
        }
    } catch (error) {
        console.error('工单状态更新异常:', error)
        ElMessage.error('请求出错')
    }
}



</script>

<style scoped>
.table-container {
    /* background-color: #ffffff; */
    /* border: 1px solid #ebeef5; */
    border-radius: 10px;
    /* padding: 20px; */
    /* margin-bottom: 30px; */
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); */
}

/* 表格滚动容器 */
.table-scroll-wrapper {
    /* height: 500px; */
    /* 固定表格高度 */
    overflow: auto;
    /* 表体滚动 */
}

/* 表头固定 */
/* .el-table th {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;
} */

/* 表格文字居中 */
::v-deep(.el-table th, .el-table td) {
    text-align: center;
}

/* 其他样式保持不变 */
.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    padding-bottom: 6px;
    border-bottom: 2px solid #333;
    display: inline-block;
}
</style>

<style lang="less" scoped>
@import "@/assets/css/index.less";
::v-deep {
    .el-container {
        display: block;
    }
    .el-table thead {
        color: #616161 !important;
    }
    .el-table th.el-table__cell {
        background-color: #f8f8f9 !important;
    }
}
</style>
